package com.caine.proxy.jdk.demo02;

import com.caine.proxy.jdk.demo02.impl.TestService02Impl;

import java.lang.reflect.Proxy;

/**
 * @Author: CaineZhu
 * @Description:
 * @Date: Created in 16:13 2020/11/4
 * @Modified By: 基于接口的代理并传入自己的实现
 */
public class JdkproxyTest02 {
    public static void main(String[] args) {
        TestService02 test = createProxy(new TestService02Impl(),TestService02.class);
        test.say02("张三");
    }

    public static <T> T createProxy(Object target,Class<T> targetInterface) {
        if (!targetInterface.isInterface()) {
            throw new IllegalStateException("targetInterface必须是接口类型!");
        } else if (!targetInterface.isAssignableFrom(target.getClass())) {
            throw new IllegalStateException("target必须是targetInterface接口的实现类!");
        }
        return (T) Proxy.newProxyInstance(JdkproxyTest02.class.getClassLoader(), target.getClass().getInterfaces(), new TestInvocationHandler02(target));
    }
}
